﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Web;
using Emgu.CV.Features2D;
using ImageHandler;
using Stamp_For_Africa_Version_2.Models;
using Stamp_For_Africa_Version_2.Repositories;


namespace Stamp_For_Africa_Version_2.Helpers
{
  public class ImageSearcher
  {
		public static Stamp FindSingleBestImageFileDb(String imageFileName, ref ImageMatch bestImageMatch, bool displayResult)
		{
      StampRepository repository = new StampRepository();
		  List<Stamp> stamps = repository.FindAllStamps(Guid.Empty).ToList();

		  Stamp bestDbStamp = null;

		  int bestMatch = 0;

		  ImageMatch contextImageMatch = new ImageMatch();
		  contextImageMatch.LoadGivenImageFromImageFile(imageFileName);


		  foreach (var stamp in stamps)
		  {

		    StampFeature feature = stamp.StampFeature;

		    MemoryStream memoryStream = new MemoryStream(feature.Features.ToArray());
		    var binFormatter = new BinaryFormatter();
		    ImageFeature[] imageFeatures = (ImageFeature[]) binFormatter.Deserialize(memoryStream);
		    contextImageMatch.TemplateImageFeatures = imageFeatures;
		    memoryStream.Close();

		    ImageHandler.ImageHandler.CalculateResults(ref contextImageMatch);

		    if (contextImageMatch.TotalPairMatches > bestMatch)
		    {
		      bestImageMatch = contextImageMatch;
		      bestMatch = bestImageMatch.TotalPairMatches;
		      bestDbStamp = stamp;
		    }

		  }
		  return bestDbStamp;
		}


    public static MatchResults FindBestImagesMatches(String imageFileName, int maxResults)
    {
      //Get the list of stamps inside the database
      StampRepository stampRepository = new StampRepository();
      StampFeatureRepository featureRepository = new StampFeatureRepository();

      List<Stamp> stamps = stampRepository.FindAllStamps(Guid.Empty).ToList();
      MatchResults matchResults = new MatchResults();
      matchResults.MaxResults = maxResults;
      Stamp bestDbStamp = null;

      int bestMatch = 0;

      ImageMatch contextImageMatch = new ImageMatch();
      contextImageMatch.LoadGivenImageFromImageFile(imageFileName);

      foreach (var stamp in stamps)
      {

        StampFeature feature = stamp.StampFeature;

        MemoryStream memoryStream = new MemoryStream(feature.Features.ToArray());
        var binFormatter = new BinaryFormatter();
         ImageFeature[] imageFeatures = (ImageFeature[])binFormatter.Deserialize(memoryStream);
        contextImageMatch.TemplateImageFeatures = imageFeatures;
        memoryStream.Close();
        contextImageMatch.MatchedDBStampId = stamp.Id;
        ImageHandler.ImageHandler.CalculateResults(ref contextImageMatch);


        matchResults.InsertImageMatch(contextImageMatch);
      }

      return matchResults;

    }
  }

}